<template>
  <div class="pagewrapper p-20">
    <div class="bg_fff pagebox h_full flex">
      <div class="pageleft flexcolumn h_full">
        <div class="p-16">
          <div class="flexbetween">
            <template v-if="!draggable">
              <div class="c_text2 mb-16">分组</div>
              <div
                class="c_primary f-14 commhover mb-16"
                @click="handleDarg(true)"
              >
                分组排序
              </div>
            </template>
            <template v-if="draggable">
              <div class="c_text2 mb-16">
                移动分组
                <el-tooltip
                  effect="dark"
                  placement="top"
                  content="移动排序实时生效"
                  popper-class="commtooltip"
                >
                  <svg-icon icon-class="iquestion" />
                </el-tooltip>
              </div>
              <div
                class="c_primary f-14 commhover mb-16"
                @click="handleDarg(false)"
              >
                返回
              </div>
            </template>
          </div>
          <div class="flexbetween">
            <el-input
              v-model="search"
              size="small"
              placeholder="搜分组"
              suffix-icon="el-icon-search"
              class="searchinput"
              @keyup.enter.native="handleQuery"
            >
            </el-input>
            <div v-hasPermi="['system:staff:addgroup']" class="btnadd flexcenter commhover" @click="handleAdd()">
              <el-tooltip
                class="item"
                effect="dark"
                content="添加一级分组"
                placement="top-start"
              >
                <i class="el-icon-plus f-16"></i>
              </el-tooltip>
            </div>
          </div>
        </div>
        <div class="left_body">
          <template v-if='!draggable'>
            <div v-for='(item,index) in groupDefault' 
              :key="index"
              class="role_item commhover flexbetween f-14 ml-12 role_w"
              :class="{ active: active == item.id }"
              @click="handleItem(item)"
            >
              <div class="flex aligncenter">
                <div class="role-title c_text f-14">{{item.groupName}}</div>
                <span class="f-12 c_999">(0)</span>
              </div>
            </div>
          </template>
          <el-tree
            v-loading="loading"
            ref="draggtree"
            :data="roleList"
            :props="defaultProps"
            node-key="id"
            default-expand-all
            @node-drag-start="handleDragStart"
            @node-drop="handleDrop"
            :draggable="draggable"
            :allow-drop="allowDrop"
            :allow-drag="allowDrag"
            class="dragtree"
            :filter-node-method="filterNode"
            :class="{ isdrag: draggable }"
          >
            <div
              class="role_item commhover flexbetween f-14"
              slot-scope="{ node, data }"
              :class="{ active: active == data.id }"
              @click="handleItem(data)"
            >
              <svg-icon
                v-if="draggable"
                class-name="draggericon f-14"
                icon-class="sort"
              />
              <div class="flex aligncenter">
                <div class="role-title c_text f-14">{{ data.groupName }}</div>
                <span class="f-12 c_999">(0)</span>
              </div>
              <el-dropdown @command="handleCommand($event, data)">
                <svg-icon
                  icon-class="more"
                  class-name="commhover roleicon f-15"
                />
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-hasPermi="['system:staff:addgroup']" command="a">新建子分组</el-dropdown-item>
                  <el-dropdown-item v-hasPermi="['system:staff:editgroup']" command="b">编辑分组</el-dropdown-item>
                  <el-dropdown-item v-hasPermi="['system:staff:deletegroup']" command="c">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </el-tree>
        </div>
      </div>
      <div class="pageright">
        <staff-table v-if="active" :key="keys" :rowid="active" :groupRow='groupRow' />
      </div>
    </div>
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="680px"
      :before-close="handleClose"
    >
      <el-form v-if="open" :model="form" :rules="rules" ref="form" label-width="160px">
        <el-form-item label="分组名称：" prop="name">
          <el-input
            v-model="form.name"
            size="small"
            maxlength="10"
            placeholder="请输入分组名称，不超过10个字"
          ></el-input>
        </el-form-item>
        <el-form-item label="可用席位数：">
          <el-radio-group v-model="form.status" @change="changeRadio">
            <el-radio :label="0">不限</el-radio>
            <el-radio :label="1">
              <el-input
                v-model="form.num"
                size="small"
                maxlength="10"
                placeholder="请输入"
                style="width: 88px"
                :disabled="form.status == 0"
                @input="(e) => (form.num = integerZeroFn(e))"
              ></el-input>
              <!--  -->
              <!--  -->
              个
            </el-radio>
          </el-radio-group>
          
        </el-form-item>
        <div class="flex" v-if="form.status == 1">
          <div class="infotitle pr-12 c_text3 f-14">说明：</div>
          <div>
            <div class="c_text3 f-14">
              1、子分组设置可用席位数的时候不判断所属父分组可用席位数。
            </div>
            <div class="c_text3 f-14">
              2、所有子分组下实际登录的企微号总数≤所属父分组可用席位数。
            </div>
          </div>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="handleClose">取 消</el-button>
        <el-button size="small" :loading='subloading' type="primary" @click="handleSubmit"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
// import RoleMain from './RoleMain.vue'
import { getsubUserGroupList, addSubUserGroup, updateSubUserGroup, delSubUserGroup } from "@/api/user";
import StaffTable from "./StaffTable.vue";
export default {
  data() {
    return {
      draggable: false,
      search: "",
      loading: "",
      groupDefault:[
        {id:-2,groupName:'全部'},
        {id:-1,groupName:'未分组'},
      ],
      roleList: [],
      draggingNode: null,
      defaultProps: {
        children: "children",
        label: "groupName",
      },
      active: -2,
      groupRow:null,
      title: "",
      open: false,
      form: {
        parentGroupId: -1,
        name: "",
        status: 0,
      },
      rules: {
        name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
      },
      keys: "",
      subloading:false,
      inputkeys:''
    };
  },
  components: {
    StaffTable,
  },
  created() {
    this.getUserGroupList();
    this.handleItem(this.groupDefault[0])
  },
  methods: {
    getUserGroupList() {
      this.loading = true;
      getsubUserGroupList()
        .then((res) => {
          this.roleList = this.handleTree(res.rows, "id", "parentGroupId");
          this.loading = false;
          // this.handleItem()
        })
        .catch(() => {
          this.loading = false;
        });
    },

    handleQuery() {
      this.$refs.draggtree.filter(this.search);
      // this.getUserGroupList();
    },

    filterNode(value, data) {
      if (!value) return true;
      return data.groupName.indexOf(value) !== -1;
    },

    // 可移动
    handleDarg(type) {
      this.draggable = type;
    },

    handleDragStart(node, ev) {
      console.log("drag start", node);
      this.draggingNode = node;
    },

    // 拖拽成功完成
    //draggingNode当前正拖拽的节点 dropNode目标节点|参考节点 dropType拖拽到参考节点的哪个位置 ev事件对象
    handleDrop(draggingNode, dropNode, dropType, ev) {
      console.log(draggingNode, dropNode, dropType, ev);
      if (this.draggingNode) {
        // 在此处可以根据业务需求，更新数据源或者调用API进行相应的操作
        console.log("拖放完成！");
        console.log("被拖动的节点：", this.draggingNode);
        console.log("接收拖放的节点：", dropNode);
      }
      this.draggingNode = null;
    },

    // 拖拽时判定目标节点能否被放置
    allowDrop(draggingNode, dropNode, type) {
      // console.log(draggingNode.level, dropNode.level);
      //注掉的是同级拖拽
      if (draggingNode.level === dropNode.level) {
        return type === "prev" || type === "next";
      } else {
        // 不同级进行处理
        return false;
      }
    },

    allowDrag(node) {
      return true;
    },

    handleAdd(item) {
      console.log('item:', item)
      this.title = "新建分组";
      if (item) {
        this.form.parentGroupId = item.id;
      }else{
        this.form.parentGroupId = -1;
      }
      this.open = true;
    },

    handleClose() {
      this.open = false;
      this.form.id = undefined
      this.form.name = ''
      this.form.num = undefined
      this.form.status = 0
    },

    handleCommand(command, item) {
      // console.log(command)
      switch (command) {
        case "a":
          this.handleAdd(item);
          break;
        case "b":
          this.handleEdit(item);
          break;
        case "c":
          this.handleDelete(item);
          break;
        default:
          break;
      }
    },

    handleEdit(item) {
      console.log('item:', item)
      this.title = "编辑角色";
      this.form.id = item.id;
      this.form.name = item.groupName;
      this.form.parentGroupId = item.parentGroupId
      if(item.wxCount == -1){
        this.form.status = 0
      //   this.form.num = undefined
      }else{
        this.form.status = 1
        // this.form.num = Number(item.wxCount)
        //   this.form.num = item.wxCount?item.wxCount: undefined
      }
      this.open = true;
      this.$nextTick(()=>{
        this.form.num = item.wxCount
      })
    },

    handleDelete(item) {
      this.$confirm("删除后子账号全部移动至未分组列表", "", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        showClose: false,
        iconClass: "el-icon-warning-outline",
        type: "warning",
      })
        .then(() => {
          delSubUserGroup(item.id).then(() => {
            this.getUserGroupList();
            this.$modal.msgSuccess("删除成功");
          });
        })
        .catch(() => {});
    },

    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (!valid) return;
        this.subloading = true;
        if (this.form.id) {
          let params = {
            id: this.form.id,
            groupName: this.form.name,
            parentGroupId: this.form.parentGroupId,
            wxCount: -1,
          };
          if (this.form.status == 1) {
            params.wxCount = this.form.num;
          }
          updateSubUserGroup(params)
            .then((res) => {
              this.$message.success("编辑成功");
              this.handleClose();
              this.getUserGroupList();
              this.subloading = false;
            })
            .catch(() => {
              this.subloading = false;
            });
        } else {
          let params = {
            groupName: this.form.name,
            parentGroupId: this.form.parentGroupId,
            wxCount: -1,
          };
          if (this.form.status == 1) {
            params.wxCount = this.form.num;
          }
          addSubUserGroup(params)
            .then(() => {
              this.$message.success("添加成功");
              this.handleClose();
              this.getUserGroupList();
              this.subloading = false;
            })
            .catch((e) => {
              this.subloading = false;
            });
        }
      });
    },

    handleItem(item) {
      this.active = item.id;
      this.groupRow = item
      console.log('item:',item, this.active)
      this.keys = Date.now();
    },

    changeRadio(val){
      if(val==0){
        this.form.num = undefined
      }
    },
    changeVal(val){
      console.log('val:', val)
      this.inputkeys = Date.now()
    },
  },
};
</script>

<style lang="scss" scoped>
.pagebox {
  border-radius: 4px;
}
.pageleft {
  width: 300px;
  border-right: 1px solid #f0f0f0;
}
.left_body {
  height: calc(100% - 102px);
  overflow-y: auto;
  padding: 0 16px 16px 16px;
}
.searchinput {
  width: 222px;
  // margin-right: ;
}
.btnadd {
  width: 32px;
  height: 32px;
  border-radius: 4px;
  border: 1px solid #e9e9e9;
}
.role_item {
  width: 100%;
  border-radius: 4px;
  position: relative;
  height: 40px;
  padding: 0 12px;
  padding-right: 6px;
  margin-bottom: 4px;

  &.active {
    background-color: #ebf2ff;
  }
  &:hover {
    background-color: #f0f0f0;
  }
  .roleicon {
    display: none;
  }

  &:hover .roleicon {
    display: inline;
  }
}
.role_w{
  width: 255px;
}
.role-title {
  max-width: 85%;
  white-space: nowrap;
  word-break: break-all;
  word-wrap: break-word;
  overflow: hidden;
  text-overflow: ellipsis;
  padding-right: 5px;
}
.pageright {
  flex: 1;
  min-height: 100%;
  overflow: hidden;
  padding: 16px;
}
.role-header {
  height: 64px;
  border-bottom: 1px solid #e0e0e0;
}
.infotitle {
  width: 160px;
  text-align: right;
}

.dragtree {
  ::v-deep .el-tree-node__content {
    height: 40px;
    border-radius: 4px;
    background-color: transparent;
    &:hover,
    &:visited,
    &:focus,
    &:active {
      background-color: transparent;
    }
  }

  ::v-deep .draggericon {
    position: absolute;
    left: -32px;
    cursor: move;
  }
  ::v-deep &.isdrag .draggericon {
    left: -42px;
  }
  ::v-deep &.isdrag .el-tree-node__expand-icon {
    margin-left: 28px;
  }
  ::v-deep .el-tree-node__content > .el-tree-node__expand-icon{
    padding: 6px 0;
  }
}
</style>